package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import entity.Student;
import entity.Subject;
import util.DBUtil;

public class SubjectDao {
	public static final int PAGE_SIZE = 5;

	public List<Subject> paging(int pageNo) {

		String sql = "select * from s_subject order by id asc limit ?,? ";

		List<Subject> datas = new ArrayList<>();
		Connection con = DBUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			ps = con.prepareStatement(sql);
			ps.setInt(1, PAGE_SIZE * (pageNo - 1));
			ps.setInt(2, PAGE_SIZE);
			rs = ps.executeQuery();
			while (rs.next()) {
				Subject s = new Subject(rs.getLong("id"), rs.getLong("gradeid"), rs.getString("subjectname"),
						rs.getInt("classhour"));

				datas.add(s);
			}

		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
			DBUtil.close(rs);
			DBUtil.close(ps);
			DBUtil.close(con);
		}
		return datas;

	}

	public int getTotalPage() {

		String sql = "select count(*) from s_subject";

		Connection con = DBUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		Student stu = null;
		int a = 0;
		try {
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			if (rs.next()) {
				a = rs.getInt(1);
			}

		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
			DBUtil.close(rs);
			DBUtil.close(ps);
			DBUtil.close(con);
		}
		// int page = (int) Math.ceil(a * 1.0 / PAGE_SIZE);
		int page = a / PAGE_SIZE + (a % PAGE_SIZE == 0 ? 0 : 1);
		return page;

	}
}
